package com.geeguo.ebuilder.client.base.tenant.provider;

import com.geeguo.ebuilder.client.base.tenant.model.DataContext;
import com.geeguo.ebuilder.client.base.tenant.model.TenantInfo;
import com.geeguo.ebuilder.client.base.tenant.proxy.TenantInfoProxy;
import com.geeguo.ebuilder.core.common.constants.HeaderConstants;
import com.geeguo.ebuilder.core.common.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TenantProvider {
    
    private static TenantInfoProxy tenantInfoProxy;
    private static boolean         inited = false;
    
    @Autowired(required = true)
    public void setTenantInfoProxy(TenantInfoProxy tenantInfoProxy) {
        TenantProvider.tenantInfoProxy = tenantInfoProxy;
        inited = tenantInfoProxy != null;
    }

    public static TenantInfo get() {
        HttpServletRequest request = ServletUtils.getRequest();
        String code = request.getHeader(HeaderConstants.TENANT);
        return getByCode(code);
    }
    
    public static TenantInfo getByCode(String code) {
        TenantInfo result = null;
        if (inited) {
            result = tenantInfoProxy.getByCode(code);
        }
        return result;
    }
    
    public static TenantInfo getByDomain(String domain) {
        TenantInfo result = null;
        if (inited) {
            result = tenantInfoProxy.getByDomain(domain);
        }
        return result;
    }

    public static DataContext getDataContext() {
        HttpServletRequest request = ServletUtils.getRequest();
        String code = request.getHeader(HeaderConstants.TENANT);
        return getDataContext(code);
    }

    public static DataContext getDataContext(String code) {
        DataContext dataContext = null;
        if (inited && StringUtils.isNotEmpty(code)) {
            TenantInfo tenant = tenantInfoProxy.getByCode(code);
            if (tenant != null) {
                dataContext = new DataContext(tenant.getCode());
            }
        }
        return dataContext;
    }

    public static void clearByCode(String code) {
        if (inited) {
            tenantInfoProxy.clearByCode(code);
        }
    }
}